/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.submit;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;

public class BtbatchPreprocessor implements CommandPreProcessor
{
	public static final String inputdir = "taskinputs";
	public static final String outputdir = "outputs";
	public static final String split_key = "_split";
	public static final int limit=500;

	public int preProcessor(UnfinishedJob job, ProgramValueBean bean) throws Exception
	{

		File taskinputdir = new File(job.getWorkdir() + File.separator + inputdir);
		taskinputdir.mkdir();

		File inputfile = new File(bean.getValue("query"));
		// each sequence has 3 fasta sequences by default
		int split = 3;
		if (bean.getValue(split_key) != null)
		{
			split = Integer.parseInt(bean.getValue(split_key));
		}

		int totalSeqs=countSeqs(new FileReader(inputfile));
		if (totalSeqs/split>500)
		{
			if (totalSeqs%500!=0)
			{
				split=totalSeqs/500+1;
			} else
			{
				split=totalSeqs/500;
			}
			
		}
		int numoffiles = splitInputs(new FileReader(inputfile), taskinputdir, split);

		bean.setValue("query", inputdir + File.separator + "$" + CommandSubmitter.TASK_ID);

		File taskoutputdir = new File(job.getWorkdir() + File.separator + outputdir);
		taskoutputdir.mkdir();
		String originalOutput = bean.getValue("txtoutput");
		if (originalOutput == null)
		{
			originalOutput = "blastall.txt";
		}
		bean.setValue("_originaloutput", originalOutput);
		bean.setValue("txtoutput", outputdir + File.separator + "$" + CommandSubmitter.TASK_ID);
		return numoffiles;
	}

	public String getOutputScript(UnfinishedJob job, ProgramValueBean bean)
	{
		String originalOutput = bean.getValue("_originaloutput");
		return "cat " + outputdir + File.separator + "* >" + originalOutput;
	}

	public final static int countSeqs(Reader inreader)throws IOException
	{
		BufferedReader in = new BufferedReader(inreader);
		int count = 0;
		String line = null;
		while ((line = in.readLine()) != null)
		{
			if (line.startsWith(">"))
			{
				// close old file.

				count++;
			}
		}
		inreader.close();
		return count;
	}
	public final static int splitInputs(Reader inreader, File targetDirectory, int splits) throws IOException
	{
		BufferedReader in = new BufferedReader(inreader);
		int count = 0;
		String line = null;
		BufferedWriter out = null;
		int totalRet = 0;
		while ((line = in.readLine()) != null)
		{
			if (line.startsWith(">"))
			{
				// close old file.

				count++;
				if (out != null)
				{
					out.flush();
				}
				if (count % splits == 1)
				{
					totalRet++;
					if (out != null)
					{
						out.flush();
						out.close();
						out = null;
					}
					out = new BufferedWriter(new FileWriter(targetDirectory.getAbsolutePath() + File.separator + totalRet));
				}

			}

			out.write(line);
			out.newLine();
		}
		out.close();
		inreader.close();
		return totalRet;
	}
}
